<template>
  <div>
    <TaskChatDialog
      :model-value="modelValue"
      title="编辑"
      width="60%"
      class="quality-dialog"
      body-class-name="dialog-quality"
      append-to-body
      @open="open"
      @close="close"
      destroy-on-close>
      <el-form ref="formRef" :model="form" label-width="120px" :rules="formRules">
        <el-row :gutter="10">
          <el-col :span="11">
            <el-form-item label="任务名称：">
              <el-input v-model="form.taskTitle" placeholder="请输入" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="负责人：">
              <el-input v-model="form.taskUserName" placeholder="请输入" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="11">
            <el-form-item label="开始时间：">
              <el-input v-model="form.planBegintime" placeholder="请输入" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="结束时间：" prop="icon">
              <el-input v-model="form.planEndtime" placeholder="请输入" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="11">
            <el-form-item label="延期原因：" required :error="customError">
              <el-select
                v-model="reasonForExtensions"
                placeholder="请选择"
                multiple
                filterable
                :reserve-keyword="true"
                @blur="checkCustomValid"
                @change="reasonForExtension"
                style="width: 100%">
                <el-option
                  v-for="(item, index) in dict.dictMap['task_info_delay_reason']"
                  :key="index"
                  :label="item.dictLabel"
                  :value="item.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="备注：" prop="icon" v-if="isRemark">
              <el-input v-model="remarks" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="22">
            <el-form-item label="任务内容：">
              <el-input v-model="form.taskDetail" placeholder="请输入" disabled type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="close">取 消</el-button>
          <el-button type="primary" :loading="loading" @click="submit">保存</el-button>
        </span>
      </template>
    </TaskChatDialog>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'
const props = defineProps({
  modelValue: Boolean,
  singleTaskData: Object,
})
import { convertToPlain } from '@/utils/task-utils.js'
import { useDictionary } from '@/use/use-dictionary'
import { updateDelayedTasks } from '@/assets/api/task'
import useUser from '@/store/user'
const dict = useDictionary(['task_info_delay_reason'])
const emit = defineEmits(['update:modelValue', 'refresh'])
const userStore = useUser()
let userInfo = userStore.userInfo

const loading = ref(false)
const form = ref({})
const formRef = ref()
let formRules = {}

const customError = ref('')
const reasonForExtensions = ref([])
const fillInTheReasonForDelay = ref([])
const isRemark = ref(false)
const remarks = ref('')

function checkCustomValid() {
  if (reasonForExtensions.value.length === 0) {
    customError.value = '请选择延期原因'
    return false
  } else {
    customError.value = ''
    return true
  }
}

function updateReasonForDelay(reasonIds) {
  fillInTheReasonForDelay.value = reasonIds.map((reasonId) => ({ reasonId }))
  isRemark.value = reasonIds.includes('7')
}

function open() {
  form.value = props.singleTaskData
  form.value.taskDetail = convertToPlain(props.singleTaskData.taskDetail)

  if (props.singleTaskData.tcTaskInfoDelays && props.singleTaskData.tcTaskInfoDelays.length > 0) {
    props.singleTaskData.tcTaskInfoDelays.forEach((item) => {
      if (userInfo.userId === item.userId) {
        reasonForExtensions.value.push(item.reasonId.toString())
        const reasonIds = reasonForExtensions.value.map((obj) => obj[Object.keys(obj)[0]])
        updateReasonForDelay(reasonIds)
        if (item.reasonId === 7) {
          remarks.value = item.reasonRemark
          isRemark.value = true
        }
      }
    })
  }
}

function reasonForExtension() {
  const reasonIds = reasonForExtensions.value.map((obj) => obj[Object.keys(obj)[0]])
  updateReasonForDelay(reasonIds)
}

function submit() {
  formRef.value.validate(async (valid) => {
    if (valid && checkCustomValid()) {
      fillInTheReasonForDelay.value.map((item) => {
        if (item.reasonId === '7') {
          item.reasonRemark = remarks.value
        }
      })

      if (props.singleTaskData.tcTaskInfoDelays && props.singleTaskData.tcTaskInfoDelays.length > 0) {
        props.singleTaskData.tcTaskInfoDelays.forEach((item) => {
          fillInTheReasonForDelay.value.forEach((item2) => {
            if (item.reasonId.toString() === item2.reasonId) {
              item2.userId = item.userId
              item2.id = item.id
              item2.taskId = item.taskId
            }
          })
        })
      }
      loading.value = true
      const params = {
        taskId: props.singleTaskData.taskId,
        tcTaskInfoDelays: fillInTheReasonForDelay.value,
      }
      updateDelayedTasks(params).then((res) => {
        if (res.code === 200) {
          ElMessage.success('修改成功')
          loading.value = false
          emit('refresh')
          close()
        } else {
          loading.value = false
        }
      })
    } else {
      checkCustomValid()
    }
  })
}

function close() {
  formRef.value.resetFields()
  emit('update:modelValue', false)
  remarks.value = ''
  reasonForExtensions.value = ''
}
</script>

<style lang="scss" scoped></style>
